#!/usr/bin/env python3

"""
Implement atoi which converts a string to an integer
"""

def string_to_integer(value):
    negative = False
    number_str = None
    contain_plus = False
    for index, ch in enumerate(value):
        if ch.isspace() and not contain_plus and not negative:
            continue
        if ch == '+' and not negative:
            contain_plus = True
            continue
        elif ch.isnumeric():
            start = index
            end = index + 1
            while end < len(value):
                ch = value[end]
                if not ch.isnumeric():
                    break
                end += 1
            number_str = value[start: end]
            break
        elif ch == '-' and not negative and not contain_plus:
            negative = True
        else:
            break
    if number_str is None:
        return 0
    result = 0
    current = 1
    for index in range(len(number_str) - 1, -1, -1):
        ch = number_str[index]
        result += int(ch) * current
        current *= 10
    if negative:
        result = -result
    if result < -2**31:
        return -2**31
    elif result >= 2**31:
        return 2**31 - 1
    else:
        return result


if __name__ == '__main__':
    assert 42 == string_to_integer('42')
    assert -42 == string_to_integer('  -42')
    assert 4193 == string_to_integer('4193 with words')
    assert 0 == string_to_integer('words and 987')
    assert -2147483648 == string_to_integer('-91283472332')
